package test.CPU;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class CPUController {
    private static int cpuClock = 0;
    private static final CPUController instance = new CPUController();
    private ScheduledExecutorService scheduler;

    private static List<CPUObserver> observers = new ArrayList<>();

    public static CPUController getInstance() {
        return instance;
    }

    private CPUController() {
        startScheduler(1.0); // 初始速率为1秒
    }

    private void startScheduler(double delayInSeconds) {
        if (scheduler != null && !scheduler.isShutdown()) {
            scheduler.shutdownNow();
        }

        scheduler = Executors.newScheduledThreadPool(1);
        long delayInMillis = (long) (delayInSeconds * 1000); // 将秒转换为毫秒
        scheduler.scheduleAtFixedRate(() -> {
            cpuClock++;
            updateObserver();
        }, 0, delayInMillis, TimeUnit.MILLISECONDS);
    }

    public static void addObserver(CPUObserver observer) {
        observers.add(observer);
    }

    public static void updateObserver() {
        for (var i : observers) {
            i.CPUUpdate(cpuClock);
        }
    }

    public void setUpdateRate(double rateInSeconds) {
        startScheduler(rateInSeconds); // 使用新的速率重启调度器
    }

    // 提供获取 cpuClock 的方法
    public int getCpuClock() {
        return cpuClock;
    }
}
